//
//  RanViewController.m
//  ChunLaiZhuangClient
//
//  Created by zouzhisheng on 16/2/15.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "RanViewController.h"
#import "CustomMenuBt.h"
#import "CustomMiFengUpTableViewCell.h"
#import "CustomDownTableViewCell.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "AppContext.h"
#import "JSONKit.h"
#import "LoginViewController.h"
#import "AccountManager.h"
#import "ProductInfoViewController1.h"
#import "AppDelegate.h"
#import <WebKit/WebKit.h>
#import "TestJSObject.h"
@interface RanViewController ()<UIWebViewDelegate>{
    WKWebViewConfiguration *config;
    WKWebView *wkWebView;
}
@property(nonatomic,strong)UIWebView *webView;
@property (nonatomic, strong) JSContext *jsContext;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) ShareView *shareView;
@end

@implementation RanViewController


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.text=@"小蜜蜂";
    titleLabel.textAlignment=NSTextAlignmentCenter;
    NSShadow *shadowAttribute = [[NSShadow alloc]init];
    shadowAttribute.shadowColor = [UIColor clearColor];
    shadowAttribute.shadowOffset = CGSizeMake(0, -1);
    titleLabel.font=[UIFont systemFontOfSize:18];
    self.navigationItem.titleView = titleLabel;
    UIButton *clearBt=[UIButton buttonWithType:UIButtonTypeCustom];
    clearBt.frame=CGRectMake(0, 0, 100, 50);
    [clearBt setTitle:@"清除缓存" forState:UIControlStateNormal];
    [clearBt setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [clearBt addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clearBt];
    
    // 一个JSContext对象，就类似于JS中的Window，只需要创建一次即可
    self.jsContext = [[JSContext alloc] init];
    
    
    _webView = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0,SCREEN_WIDTH,SCREEN_HEIGHT-64-49)];
    _webView.delegate = self;
    _webView.allowsInlineMediaPlayback=YES;
    _webView.scrollView.bounces = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    [_webView sizeToFit];
    [self.view addSubview:_webView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut) name:ACCOUNT_WILLDID_LOGOUT_NOTIFICATION object:nil];
    
    [self loadWebView];

    // Do any additional setup after loading the view from its nib.
}
-(void)clearAction:(UIButton*)bt{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];

}
#pragma mark-登陆回调
-(void)loginOut{
    NSLog(@"userid==%@",APP_CONTEXT.account.data.customer_id);
    [self loadWebView];
}
-(void)loadWebView{
   // [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL_XMF]]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.chunlaizhuang.com/bee/ios/"]]];
}

- (void)loadExamplePage:(UIWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"ExampleApp" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [webView loadHTMLString:appHtml baseURL:baseURL];
}
//- (void)webViewDidStartLoad:(UIWebView *)webView{
//    [[LKDHud shareHud] showLoadingView];
//}
//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    [[LKDHud shareHud] hideLoadingView];
//}


-(void)toProductDetail:(NSString *)productID{
    dispatch_async(dispatch_get_main_queue(), ^{
        ProductInfoViewController1 *productVC=[[ProductInfoViewController1 alloc] initWithProductId:productID];
        [self.navigationController pushViewController:productVC animated:YES];

    });
    }
-(void)doShare:(NSString*)content{
            UIAlertView *alet=[[UIAlertView alloc] initWithTitle:@"分享" message:[NSString stringWithFormat:@"%@",content] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alet show];
}


-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //网页加载完成调用此方法
    
    //iOS调用js
    
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

     //第二种情况，js是通过对象调用的，我们假设js里面有一个对象 testobject 再调用方法
     //首先创建我们新建的类，将他赋值给js的对象
     
     TestJSObject *testJO=[TestJSObject new];
    testJO.vcDelegate=self;
     context[@"nativeCall"]=testJO;
    
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    //网页加载失败 调用此方法
}
-(void)shareAction:(NSString*)shareContent{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.backView.alpha = 1.f;
        __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:.3f animations:^{
            weakSelf.shareView.top = SCREEN_HEIGHT - self.shareView.height;
            weakSelf.shareView.shareContent=shareContent;
        }];
        
    });

    
}

- (UIView *)backView {
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [_backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeShareViewAction:)]];
        _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f];
        [self.navigationController.view addSubview:_backView];
    }
    return _backView;
}
#pragma mark -shareView
- (ShareView *)shareView {
    if (!_shareView) {
        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 199.f)];
        __weak typeof(_shareView) weakShareView = _shareView;
        __weak typeof (self) weakSelf = self;
        _shareView.closeShareViewBlock = ^(){
            weakSelf.backView.alpha = 0.f;
            [UIView animateWithDuration:.3f animations:^{
                weakShareView.top = SCREEN_HEIGHT;
            }];
        };
        [self.tabBarController.view addSubview:_shareView];
        
    }
    return _shareView;
}

- (void)closeShareViewAction:(UITapGestureRecognizer *)gesture {
    self.backView.alpha = 0.f;
    [UIView animateWithDuration:.3f animations:^{
        self.shareView.top = SCREEN_HEIGHT;
    }];
}

- (void)shareWXSuccess:(NSNotification *)notify {
    self.backView.alpha = 0.f;
    self.shareView.hidden = YES;
    SendMessageToWXResp *response = notify.object;
    if (response.errCode == 0) {
        [self showHudWithText:@"分享成功"];
    } else {
        [[LKDHud shareHud] showtip:response.errStr];
    }
}
- (void)showHudWithText:(NSString *)str {
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.contentColor = [UIColor blackColor];
    [self.view addSubview:HUD];
    HUD.labelText = str;
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_select_selectd"]] ;
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(2);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
